// 老的打包方式，打包成整包umd文件，保留这个配置，仅仅为了有时候老环境线上调试用本地js替换用

import { viteCommonjs } from '@originjs/vite-plugin-commonjs';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import path from 'path';
import { defineConfig } from 'vite';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
import envCompatible from 'vite-plugin-env-compatible';
import { createHtmlPlugin } from 'vite-plugin-html';
import VappMeta from './AssetPack/vapp-meta-data.json';
import prefixer from 'postcss-prefix-selector';
import autoprefixer from 'autoprefixer';

function getEnvInfo() {
  let envInfo = {};
  envInfo = { env: 'vt1' };

  if (process.env.NODE_ENV === 'development') {
    const envUrl = '../public_node_modules/visual_components_web/env.js';
    envInfo = require(envUrl);
    return envInfo;
  }

  return envInfo;
}

function getAllEnvProxy(proxy, envInfo) {
  const { envConf } = envInfo || {};
  const allProxy = {};

  const excludes = [
    '/recordRules',
    '/codehub',
    '/iamtmp/keystone/auth/getToken',
    '/idp-edit-war',
    '/localApi',
    '/mock',
    '/translateText',
  ];
  Object.entries(envConf).map(([env]) => {
    Object.entries(proxy).map(([i]) => {
      const key = `/${env}${i}`;
      allProxy[key] = {
        target: excludes.includes(i) ? proxy[i].target : envConf[env]?.baseUrl,
        changeOrigin: true,
        secure: false,
        xfwd: false,
        rewrite: _path => _path.replace(new RegExp(`^/${env}`), ''),
      };
    });
  });
  return allProxy;
}

let baseUrl = '';
const envInfo = getEnvInfo();
let codehubUrl = '';
let translateTextApiUrl = '';
if (envInfo) {
  const { env, envConf } = envInfo;
  if (env && envConf) {
    baseUrl = envConf[env].baseUrl;
    codehubUrl = envInfo.codehubUrl;
    translateTextApiUrl = envInfo.translateTextApiUrl;
  }
}

export default defineConfig({
  define: {
    'process.env.NODE_ENV': process.env.NODE_ENV === 'development' ? JSON.stringify('development') : JSON.stringify('production'),
    'process.env.project_folder': JSON.stringify(path.basename(__dirname)),
    'process.env.xvueNameSpace': JSON.stringify(VappMeta.xvueNameSpace),
    'process.env.xvueNameSpace_': JSON.stringify(`${VappMeta.xvueNameSpace.replace(/-/g, '_')}_`),
    'global': 'window', // 通用地图global报错兼容
  },
  resolve: {
    alias: [
      {
        find: /^~/,
        replacement: '',
      },
      {
        find: '@',
        replacement: path.resolve(__dirname, 'src'),
      },
      {
        find: 'lib',
        replacement: path.resolve(__dirname, 'lib'),
      },
      {
        find: 'public',
        replacement: path.resolve(__dirname, 'public'),
      },
    ],
    extensions: [
      '.mjs',
      '.js',
      '.ts',
      '.jsx',
      '.tsx',
      '.json',
      '.vue',
    ],
  },
  plugins: [
    vue(),
    vueJsx(),
    viteCommonjs(),
    envCompatible(),
    cssInjectedByJsPlugin(),
    createHtmlPlugin({
      inject: {
        data: {
          title: 'componentsDemo.v0001',
        },
      },
    }),
  ],
  base: '/',
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
    postcss: {
      plugins: [
        prefixer({
          prefix: `.${VappMeta.xvueNameSpace}`,
          exclude: [`.${VappMeta.xvueNameSpace}`],
          transform(prefix, selector, prefixedSelector, filePath, rule) {
            // 开发环境不执行添加前缀功能
            if (process.env.NODE_ENV === 'development') {
              return selector;
            }
            if (filePath.match(/node_modules/)) {
              return selector; // Do not prefix styles imported from node_modules
            }
            return prefixedSelector;
          },
        }),

        autoprefixer({}) // add options if needed
      ],
    }
  },
  server: {
    strictPort: false,
    port: 8068,
    host: 'localhost.huawei.com',
    open: true,
    proxy: {},
  },
  commonjsOptions: {
    esmExternals: true,
  },
  build: {
    minify: false,
    lib: {
      name: 'componentsDemo',
      entry: path.resolve(__dirname, 'src/components/index-old.js'),
      formats: ['umd'],
      fileName: format => 'componentsDemo.umd.min.js',
    },
    rollupOptions: {
      external: ['vue', 'element-plus', 'vuex', 'vue-router', 'axios', 'echarts', 'xe-utils', 'vxe-table'],
      output: {
        dir: './AssetPack/web/web-components/lib',
        globals: {
          vue: 'Vue',
          'element-plus': 'ElementPlus',
          vuex: 'Vuex',
          'vue-router': 'VueRouter',
          axios: 'axios',
          echarts: 'echarts',
          'xe-utils': 'XEUtils',
          'vxe-table': 'VXETable',
        },
        inlineDynamicImports: true,
        name: 'componentsDemo',
        exports: 'named',
      },
    },
    commonjsOptions: {
      includes: ['node_modules/**/**.js'],
      transfromMixedEsModules: true,
    },
  },
});
